package geektime.concurrent.race;
/**
 *
 **/

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @Author weiwei
 * @Date 2021-12-31 10:36
 * @description
 **/
public class MyPolicy {

    final int genThreadInPool = 2; //不超过8
    final int computeThreadInPool = 16; //不超过16
    MyShareData ssd;

    public MyPolicy() {
        ssd = new MyShareData();
        ssd.initGenSignals(genThreadInPool);
        ssd.initCompSignals(computeThreadInPool);
        ssd.initExchange();
    }

    public long go() throws Exception {
        ExecutorService genThreadPool = Executors.newFixedThreadPool(genThreadInPool);
        ExecutorService computeThreadPool = Executors.newFixedThreadPool(computeThreadInPool);

        //使用自定义方法A计算
        long startTime = System.currentTimeMillis();
        System.out.println("开始自定义A方法计算计时: " + startTime);

        for (int tp = 0; tp < genThreadInPool; tp++) {
            MyGen gen = new MyGen(ssd, SimpleShareData.COUNT / genThreadInPool, tp);
            genThreadPool.execute(gen);
        }

        ssd.getGenSig().await();
        System.out.println("生成随机数个数:"+ssd.getScore().size());
        long genTime = System.currentTimeMillis();
        System.out.println("产生随机数时长: " + (genTime - startTime));


        for (int tp = 0; tp < computeThreadInPool; tp++) {
            MyCompute compute = new MyCompute(ssd, SimpleShareData.COUNT / computeThreadInPool, tp);
            computeThreadPool.execute(compute);
        }
        ssd.getCompSig().await();
        List<Integer> share = ssd.getShare();
        share.sort(Collections.reverseOrder());
        for (int i = 0; i < SimpleShareData.BUFSIZE; i++) {
            ssd.getTop()[i] = share.get(i);
        }
        printTop();

        long sortTime = System.currentTimeMillis();
        System.out.println("自定义A方法计算时长: " + (sortTime - genTime));

        computeThreadPool.shutdown();
        genThreadPool.shutdown();
        return sortTime - startTime;
    }
    void printTop() {
        System.out.println("前10成绩为:");
        for (int j = 0; j <= 10; j++) {
            System.out.print(ssd.getTop()[j] + " ");
        }
        System.out.println();
    }
}
